/*
 * Created on 07.12.2012
 *
 */
package de.denniswilmsmann.jmslogger.activemq;

import javax.jms.Connection;
import javax.jms.ConnectionFactory;
import javax.jms.JMSException;
import javax.jms.Message;
import javax.jms.MessageListener;
import javax.jms.ObjectMessage;
import javax.jms.Session;
import javax.jms.TextMessage;
import javax.jms.Topic;
import javax.jms.TopicSubscriber;

import org.apache.activemq.ActiveMQConnection;
import org.apache.activemq.ActiveMQConnectionFactory;

/*
 * $Log: $
 */

public class Consumer {

    private static String url = ActiveMQConnection.DEFAULT_BROKER_URL;

    private static String subject = "TestTopic";
    private final String name;
    private Connection connection;
    private TopicSubscriber subscriber;

    public Consumer(String name) {
        this.name = name;
    }

    public void destroy() {
        try {
            subscriber.close();
            connection.close();
        } catch (JMSException e) {
            e.printStackTrace();
        }
    }

    public void consumeMessage() throws JMSException {
        ConnectionFactory connectionFactory = new ActiveMQConnectionFactory(url);
        connection = connectionFactory.createConnection();
        connection.setClientID(name);
        connection.start();

        Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
        Topic topic = session.createTopic(subject);

        subscriber = session.createDurableSubscriber(topic, name);
        subscriber.setMessageListener(new MessageListener() {

            @Override
            public void onMessage(Message message) {
                try {
                    if (message instanceof TextMessage) {
                        TextMessage textMessage = (TextMessage) message;
                        System.out.println(name + " has received text message '" + textMessage.getText() + "'");
                    } else if (message instanceof ObjectMessage) {
                        ObjectMessage objectMessage = (ObjectMessage) message;
                        MyMessage m = (MyMessage) objectMessage.getObject();
                        System.out.println(name + " has received object message '" + m.getText() + "'");
                    }
                } catch (JMSException e) {
                    e.printStackTrace();
                }
            }
        });

        // connection.close();
    }
}
